<?php

namespace app\components\weixin;

use Yii;
use app\components\Fun;
use app\components\API;
use \app\models\User;
use app\components\weixin\ErrorCode;

/**
 * Description of Weixin
 *
 * @author songshuai
 */
class WeixinApp {

    private $appid = '1108775182'; ///qq小程序的id
    private $AppSecret = '6jxk5OIbZFTyvIBX'; //小程序密钥
    private $sessionKey = '';
    private $openid = '';
    private $info = null;
    private $code = '';

    public function Login() {
        $encryptedData = Yii::$app->request->post("encryptedData");
        $iv = Yii::$app->request->post("iv");
        $signature = Yii::$app->request->post("signature");
        $this->code = Yii::$app->request->post("code");
        $url = 'https://api.q.qq.com/sns/jscode2session?appid=' . $this->appid . '&secret=' .
                $this->AppSecret . '&js_code=' . $this->code . '&grant_type=authorization_code';
        $data = Fun::curl_get($url);
        $json = json_decode($data, true);
        if (empty($json['openid'])) {
            \app\models\Error::addmsg("小程序登录错误,获取sessionKey错误");
            API::echo_json(0, [
                'session' => '',
                'id' => ''
            ]);
        }
        $this->openid = $json['openid'];
        $this->sessionKey = $json['session_key'];
        // print_r($json);exit;
        /*         * Array
          (
          [errcode] => 0
          [errmsg] =>
          [openid] => EAB666E43A0E5CD1E417A0628DAF2442
          [session_key] => b3Rxb3cxMlZLRzIxdWNBaw==
          [uin] =>
          [unionid] =>
          ) */
        $decr = $this->decryptData($encryptedData, $iv, $data);
        if ($decr !== 0) {
            //  API::echo_json(1, '登录错误,获取用户信息失败,错误:' + $decr);
            \app\models\Error::addmsg("小程序登录错误,获取用户信息失败" . $decr);
            API::echo_json(0, [
                'session' => '',
                'id' => ''
            ]);
        }
        $this->info = $data;/**Array
(
    [avatarUrl] => https://thirdqq.qlogo.cn/qqapp/1108775182/EAB666E43A0E5CD1E417A0628DAF2442/100
    [city] => 徐汇
    [country] => 中国
    [gender] => 1
    [language] => zh_CN
    [nickName] => 宋帅
    [openId] => EAB666E43A0E5CD1E417A0628DAF2442
    [province] => 上海
    [unionId] => 
    [watermark] => Array
        (
            [appid] => 1108775182
            [timestamp] => 1555064202
        )

)*/
        $this->LoginData();
    }

    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public function decryptData($encryptedData, $iv, &$data) {
        if (strlen($this->sessionKey) != 24) {
            return ErrorCode::$IllegalAesKey;
        }
        $aesKey = base64_decode($this->sessionKey);


        if (strlen($iv) != 24) {
            return ErrorCode::$IllegalIv;
        }
        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result, true);

        if ($dataObj == NULL) {
            return ErrorCode::$IllegalBuffer;
        }
        if ($dataObj['watermark']['appid'] != $this->appid) {
            return ErrorCode::$IllegalBuffer;
        }

        $data = $dataObj;
        return ErrorCode::$OK;
    }

    /**
     * 记录用户的数据到数据库
     */
    private function LoginData() {
        /*  print_r($this->info);
          var_dump(Yii::$app->session->getId());
          exit; */
        $user = new User;
        $one = $user->is_bd([
            'uid' => $this->openid,
            'bind_type' => User::bindtype_weixin,
            'username' => $this->info['nickName'],
            'avatar' => $this->info['avatarUrl']
        ]);
        if ($one === false) {
            // API::echo_json(1,"登录错误");
            \app\models\Error::addmsg("小程序登录错误");
            API::echo_json(0, [
                'session' => '',
                'id' => ''
            ]);
        } else {
            $userid = $one->id;
            $one->login();
            //Yii::$app->user->login($one, 3600 * 2);
            API::echo_json(0, [
                'session' => Yii::$app->session->getId(),
                'id' => $userid,
                'openid'=>$this->openid
            ]);
        }
    }

}
